import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_with_title_dialog/common_edit_with_title_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_sliver_delegate/common_sliver_delegate.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_move_page_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_view_model.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/handle_media_library_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_detail_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_library_play_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_settings_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/poster_detail_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_video_upload_service.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/ui/index/even/location_changed_event.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'bean/SelfStorageInfoBean.dart';
import 'bean/StorageInfoBean.dart';
import 'bean/media_library_index_response_bean.dart';
import 'bean/play_num_bean.dart';
import 'even/media_library_index_refresh_even.dart';
import 'widgets/media_library_index_filter_bar_widget.dart';

/// 媒体资料库首页
///
/// @author: zengxiangxi
/// @createTime: 2/3/21 1:08 PM
/// @specialDemand:
class MediaLibraryIndexPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "MediaLibraryIndexPage";

  @override
  MediaLibraryIndexPageState createState() => MediaLibraryIndexPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(
      context,
      MediaLibraryIndexPage(),
      routeName: MediaLibraryIndexPage.ROUTER,
    );
  }
}

class MediaLibraryIndexPageState
    extends BaseState<MediaLibraryIndexPage> with
    AutomaticKeepAliveClientMixin,
    NavigatorPageMixin {
  MediaLibraryIndexViewModel viewModel;

  PageController _pageController;
  ScrollController _scrollController;
  StreamSubscription _streamSubscription;
  StreamSubscription _mediaLibraryStreamSubscription;
  StreamSubscription _terminalNumRefreshSubscription;
  int _allTerminalSize = 0;
  PicNumBean _picNumBean;
  Function(PicNumBean) picNumFunction;

  String _latestGps;

  MediaLibraryVideoUploadService _mediaVideoUploadService;

  ///获取state
  static MediaLibraryIndexPageState of(BuildContext context) {
    final MediaLibraryIndexPageState result =
    context.findAncestorStateOfType<MediaLibraryIndexPageState>();
    return result;
  }

  @override
  void initState() {
    super.initState();
    _mediaVideoUploadService = MediaLibraryVideoUploadService.getInstance();
    MediaLibraryIndexViewModel.EMPTY_FLAG = false;
    VgEventBus.global.streamController.stream.listen((event) {
      if (event is LocationChangedEvent) {
        print("收到gps更新的:" + event?.gps);
        if(StringUtils.isNotEmpty(event?.gps??"")){
          if(event?.gps == _latestGps){
            return;
          }
          _latestGps = event?.gps;
        }
      }
    });
    picNumFunction = (picNumBean){
      setState(() {
        _picNumBean = picNumBean;
      });
    };
    viewModel = MediaLibraryIndexViewModel(this, picFunction: picNumFunction);
    _pageController = PageController(keepPage: true, initialPage: 1);
    _scrollController = ScrollController();
    // viewModel?.getCache();
    viewModel?.refresh();
    viewModel?.getStorageInfo(context);
    viewModel?.getSelfStorageInfo(context);
    viewModel?.getPicNum(context);
    _streamSubscription =
        VgEventBus.global.on<MediaLibraryRefreshEven>()?.listen((event) {
          viewModel?.refreshMultiPage();
          viewModel?.getStorageInfo(context);
          viewModel?.getSelfStorageInfo(context);
          viewModel?.getPicNum(context);
        });
    _mediaLibraryStreamSubscription =
        VgEventBus.global.on<MonitoringMediaLibraryIndexClass>()?.listen((event) {
          viewModel?.refreshMultiPage();
          viewModel?.getStorageInfo(context);
          viewModel?.getSelfStorageInfo(context);
          viewModel?.getPicNum(context);
        });
    addPageListener(onPop: () {
      viewModel?.refreshMultiPage();
      // viewModel?.getStorageInfo(context);
      // viewModel?.getSelfStorageInfo(context);
      viewModel?.getPicNum(context);
    });

    String cacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        setState(() {
          Map map = json.decode(jsonStr);
          IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(map);
          if(bean != null){
            if(bean.data != null
                && bean.data.bindTerminalList != null){
              _allTerminalSize = bean.data.bindTerminalList.length;
              if(_allTerminalSize == 0){
                MediaLibraryIndexViewModel.EMPTY_FLAG = true;
                viewModel = MediaLibraryIndexViewModel(this, picFunction: picNumFunction);
                viewModel?.refresh();
                viewModel?.getStorageInfo(context);
                viewModel?.getSelfStorageInfo(context);
                viewModel?.getPicNum(context);
              }
            }
          }
        });
      }
    });

    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if(event is TerminalNumRefreshEvent){
        if((event?.num??0) != 0 && _allTerminalSize == event?.num){
          //数量不变
          print("终端数量未变，不执行");
          return;
        }
        _allTerminalSize = event?.num??0;
        if(_allTerminalSize == 0){
          MediaLibraryIndexViewModel.EMPTY_FLAG = true;
          viewModel = MediaLibraryIndexViewModel(this, picFunction: picNumFunction);
        }else{
          MediaLibraryIndexViewModel.EMPTY_FLAG = false;
          viewModel = MediaLibraryIndexViewModel(this, picFunction: picNumFunction);
        }
        viewModel?.refresh();
        viewModel?.getStorageInfo(context);
        viewModel?.getSelfStorageInfo(context);
        viewModel?.getPicNum(context);
      }
      if(event is MediaMovePageEvent){
        _pageController.animateToPage(event.pageNo, duration: DEFAULT_ANIM_DURATION, curve: Curves.linear);
      }
    });
  }


  @override
  void dispose() {
    _terminalNumRefreshSubscription?.cancel();
    _pageController?.dispose();
    _scrollController?.dispose();
    _streamSubscription?.cancel();
    _mediaLibraryStreamSubscription?.cancel();
    _videoController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: Column(
        children: [
          Container(
            color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            height: ScreenUtils.getStatusBarH(context),
          ),
          _toMainColumnWidget(),
        ],
      ),
    );
  }
  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }
  Widget _toMainColumnWidget() {
    return Expanded(
      child: ScrollConfiguration(
        behavior: MyBehavior(),
        child: NestedScrollView(
          controller: _scrollController,
          physics: BouncingScrollPhysics(),
          // innerScrollPositionKeyBuilder: () {
          //   return Key("123");
          // },
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){
            return[
              SliverToBoxAdapter(
                child: _toTopBarWidget(),
              ),
              SliverPersistentHeader(
                pinned: true,
                key: UniqueKey(),
                delegate: CommonSliverPersistentHeaderDelegate(
                  maxHeight: 57,
                  minHeight: 57,
                  child: MediaLibraryIndexFilterBarWidget(
                    pageController: _pageController,
                    picNumBean: _picNumBean,
                    totalValueNotifier: viewModel?.totalValueNotifier,
                    onAddTap: throttle(()  async {
                      _processUpload();
                      await Future.delayed(Duration(milliseconds: 2000));
                    }),
                    onHandleTap: (){
                      HandleMediaLibraryPage.navigatorPush(context, _getPageType());
                    },
                  ),
                ),
              )
            ];
          },
          body: Column(
            children: [
              _toUploadView(),
              Expanded(
                child: PageView(
                  controller: _pageController,
                  physics: ClampingScrollPhysics(),
                  children: <Widget>[
                    // _toPlaceHolderWidget(
                    //     child: MediaLibraryIndexGridPage(
                    //       list: data,
                    //       onTap: _onTap,
                    //       onDelete: _onDelete,
                    //       onUpateName: _onUpdateName,
                    //       canSelect: false,
                    //     )),
                    MediaLibraryPlayPage(pageType: MediaLibraryPlayPage.TYPE_PLAYED, gps: _latestGps),
                    MediaLibraryPlayPage(pageType: MediaLibraryPlayPage.TYPE_PLAYING, gps: _latestGps),
                    MediaLibraryPlayPage(pageType: MediaLibraryPlayPage.TYPE_WAIT_PLAY, gps: _latestGps),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );





    // Column(
    //   children: <Widget>[
    //     MediaLibraryIndexTopBarWidget(
    //       totalValueNotifier: viewModel?.totalValueNotifier,
    //       onAddTap: throttle(()  async {
    //         _processUpload();
    //         await Future.delayed(Duration(milliseconds: 2000));
    //       }),
    //       onHandleTap: (){
    //         HandleMediaLibraryPage.navigatorPush(context);
    //       },
    //     ),
    //     Expanded(
    //       child: _toMainPlaceHolderWidget(),
    //     )
    //   ],
    // )
  }

  ///上传布局
  Widget _toUploadView(){
    return StreamBuilder<List<UploadMediaLibraryItemBean>>(
        stream: _mediaVideoUploadService?.uploadServiceStream?.stream,
        initialData: _mediaVideoUploadService?.getAllUploadingInfoList(),
        builder: (context, AsyncSnapshot<List<UploadMediaLibraryItemBean>> snapshot) {
          List<UploadMediaLibraryItemBean> infoList = snapshot?.data;
          if(infoList == null || infoList.isEmpty){
            return Container();
          }else{
            UploadMediaLibraryItemBean firstItem = infoList.first;
            double padding = (infoList.length > 1)?12:15;
            return Container(
                padding: EdgeInsets.only(left: 12, right: 12, top: padding, bottom: padding),
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                height: 67,
                child: Column(children: <Widget>[
                  Row(
                    children: <Widget>[
                      _toCoverWidget(infoList),
                      SizedBox(
                        width: 5,
                      ),
                      Text("正在上传视频",
                          style: TextStyle(color: Color(0xFF999999), fontSize: 13)),
                      Spacer(),
                      GestureDetector(
                        child: Container(
                          padding: const EdgeInsets.only(left: 10,right: 10),
                          height: 24,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                                color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                                width: 0.5),
                          ),
                          child: Text(
                            "终止",
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        onTap: () async{
                          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                              title: "提示",
                              content: "确定终止上传视频？",
                              cancelText: "取消",
                              confirmText: "确定",
                              confirmBgColor: ThemeRepository.getInstance()
                                  .getMinorRedColor_F95355());
                          if (result ?? false) {
                            if(infoList.length > 1){
                              _mediaVideoUploadService?.cancelAll(firstItem?.id);
                            }else{
                              _mediaVideoUploadService?.cancelUpload(firstItem?.id, firstItem?.localUrl,);
                            }

                          }

                          // _viewModel.uploadModel!.removeCurrentBean();
                        },
                      )
                    ],
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  Container(
                    height: 2,
                    child: StreamBuilder<UploadMediaLibraryItemBean>(
                      stream: _mediaVideoUploadService?.uploadingStreamMap[firstItem?.id]?.stream,
                      initialData: _mediaVideoUploadService?.getCurrentUploadingInfoFromAll(firstItem?.id),
                      builder: (context, AsyncSnapshot<UploadMediaLibraryItemBean> snapshot){
                        UploadMediaLibraryItemBean item = snapshot?.data;
                        return LinearProgressIndicator(
                            value: (item?.progress ?? 0)/100.0,
                            backgroundColor: Color(0xFFCEE0F9),
                            valueColor:
                            new AlwaysStoppedAnimation<Color>(Color(0xFF179ECE)));
                      },

                    ),
                  ),
                ]));
          }
        }
    );
  }

  ///根据上传视频的数据获取封面布局
  Widget _toCoverWidget(List<UploadMediaLibraryItemBean> infoList){
    if(infoList.length == 1){
      UploadMediaLibraryItemBean item = infoList.elementAt(0);
      return Container(
        width: 30,
        height: 30,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: <Widget>[
            item?.videoLocalCover != null
                ? Image.file(
              File(item?.videoLocalCover??""),
              width: 30,
              height: 30,
              cacheWidth: 30,
              cacheHeight: 30,
              fit: BoxFit.cover,
            )
                : Container(
              width: 30,
              height: 30,
            ),
            Image.asset(
              "images/icon_smart_home_video_play.png",
              width: 10,
              height: 10,
            )
          ],
        ),
      );
    }else{
      UploadMediaLibraryItemBean firstItem = infoList.elementAt(0);
      UploadMediaLibraryItemBean secondItem = infoList.elementAt(1);
      return Stack(
        children: [
          Container(
            width: 30,
            height: 30,
            child: Stack(
              alignment: AlignmentDirectional.center,
              children: <Widget>[
                secondItem?.videoLocalCover != null
                    ? Image.file(
                  File(secondItem?.videoLocalCover??""),
                  width: 30,
                  height: 30,
                  cacheWidth: 30,
                  cacheHeight: 30,
                  fit: BoxFit.cover,
                )
                    : Container(
                  width: 30,
                  height: 30,
                ),
                Image.asset(
                  "images/icon_smart_home_video_play.png",
                  width: 10,
                  height: 10,
                )
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 6, top: 6),
            child: Container(
              width: 30,
              height: 30,
              child: Stack(
                alignment: AlignmentDirectional.center,
                children: <Widget>[
                  firstItem?.videoLocalCover != null
                      ? Image.file(
                    File(firstItem?.videoLocalCover??""),
                    width: 30,
                    height: 30,
                    cacheWidth: 30,
                    cacheHeight: 30,
                    fit: BoxFit.cover,
                  )
                      : Container(
                    width: 30,
                    height: 30,
                  ),
                  Image.asset(
                    "images/icon_smart_home_video_play.png",
                    width: 10,
                    height: 10,
                  )
                ],
              ),
            ),
          ),
        ],
      );
    }
  }

  String _getPageType(){
    if(_pageController.page >= 1.51){
      return MediaLibraryPlayPage.TYPE_WAIT_PLAY;
    }else if(_pageController.page >= 0.51){
      return MediaLibraryPlayPage.TYPE_PLAYING;
    }else if(_pageController.page <=0.49){
      return MediaLibraryPlayPage.TYPE_PLAYED;
    }else{
      return MediaLibraryPlayPage.TYPE_PLAYING;
    }
  }

  Widget _toTopBarWidget(){
    int total = 500;
    return Container(
      color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      padding: EdgeInsets.only(left: 15),
      child: Column(
        children: [
          Container(
            height: 44,
            child: Row(
              children: <Widget>[
                ValueListenableBuilder(
                  valueListenable: viewModel?.storageInfoNotifier,
                  builder: (BuildContext context, StorageDataBean storageInfo, Widget child) {
                    if(storageInfo != null){
                      int num = storageInfo.hsnNum??1;
                      int size = storageInfo.spacesize??500;
                      total = num*size;
                      if(total == 0){
                        total = 500;
                      }
                    }
                    return Text(
                      "免费云存储空间·${showMemoryStr(total)}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                          fontSize: 17,
                          height: 1.2,
                          fontWeight: FontWeight.w600),
                    );
                  },
                ),
                Spacer(),
                Visibility(
                  visible: false,
                  child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: (){
                        // onHandleTap?.call();
                      },
                      child: Container(
                        padding: EdgeInsets.only(right: 15),
                        child: Text(
                          "购买",
                          style: TextStyle(
                              color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                              fontSize: 13,
                              height: 1.2
                          ),
                        ),
                      )
                  ),
                ),
              ],
            ),
          ),
          ValueListenableBuilder(
            valueListenable: viewModel?.selfStorageInfoNotifier,
            builder: (BuildContext context, SelfStorageDataBean storageInfo, Widget child) {
              double width = ScreenUtils.screenW(context) - 30;
              double picWidth = (((storageInfo?.picSpacesize??0)*1.0)/(total*1024)) * width;
              double videoWidth = (((storageInfo?.videoSpacesize??0)*1.0)/(total*1024)) * width;
              double audioWidth = 0;
              if(picWidth>width){
                picWidth = width;
              }
              if(videoWidth>width){
                videoWidth = width - picWidth - audioWidth;
              }
              double percent = 0;
              if(total > 0){
                percent = (((storageInfo?.picSpacesize??0) + (storageInfo?.videoSpacesize??0)) * 100.0)/(total*1024);
              }
              print("000000000000000000width:" + width.toString());
              print("000000000000000000picWidth:" + picWidth.toString());
              print("000000000000000000videoWidth:" + videoWidth.toString());
              print("000000000000000000audioWidth:" + audioWidth.toString());
              return Column(
                children: [
                  Container(
                    height: 20,
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "已用${storageInfo?.getStorageStr()??"0MB"}",
                      style: TextStyle(
                        color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                        fontSize: 14,
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 4,
                  ),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(2),
                    child: Container(
                      height: 12,
                      color: Color(0x21FFFFFF),
                      margin: EdgeInsets.only(right: 15),
                      child: Row(
                        children: [
                          Container(
                            height: 12,
                            width: picWidth??0,
                            decoration: BoxDecoration(
                              color: Color(0xFF00C6C4),
                            ),
                          ),
                          Container(
                            height: 12,
                            width: videoWidth??0,
                            decoration: BoxDecoration(
                              color: Color(0xFF1890FF),
                            ),
                          ),
                          Container(
                            height: 12,
                            width: audioWidth??0,
                            decoration: BoxDecoration(
                              color: Color(0xFFFFB714),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Row(
                    children: [
                      _toSampleWidget(0xFF00C6C4, "图片", storageInfo?.picSpacesize??0),
                      Visibility(
                        visible: (storageInfo?.picSpacesize??0)>0,
                        child: SizedBox(width: 15,),
                      ),
                      _toSampleWidget(0xFF1890FF, "视频", storageInfo?.videoSpacesize??0),
                      Visibility(
                        visible: (storageInfo?.videoSpacesize??0)>0,
                        child: SizedBox(width: 15,),
                      ),
                      _toSampleWidget(0xFFFFB714, "音频", 0),
                      Spacer(),
                      Text(
                        (percent <= 0)?"0%":"${(percent??0).toStringAsFixed(2)}%",
                        style: TextStyle(
                            color: Color(0xFFBFC2CC),
                            fontSize: 11,
                            height: 1.2
                        ),
                      ),
                      SizedBox(width: 15,)
                    ],
                  ),
                ],
              );
            },
          ),
          SizedBox(
            height: 16,
          ),
        ],
      ),
    );
  }

  String showMemoryStr(int mbValue) {
    if (mbValue == null || mbValue <= 0) {
      return "0MB";
    }
    if (mbValue < 1024) {
      return "${mbValue}MB";
    }
    if(mbValue % 1024 == 0){
      return "${(mbValue / 1024)}GB";
    }else{
      return "${((mbValue*1.0) / 1024).toStringAsFixed(2)}GB";
    }

  }

  String getStorageStr(int size){
    if(size <= 1024){
      return size.toStringAsPrecision(3) + "KB";
    }else if(size > 1024 && size <= 1024*1024){
      return (size/1024).toStringAsPrecision(3) + "MB";
    }else{
      return (size/(1024*1024)).toStringAsPrecision(3) + "G";
    }
  }

  Widget _toSampleWidget(int color, String type, int size){
    return Visibility(
      visible: (size??0)>0,
      child: Container(
        alignment: Alignment.center,
        child: Row(
          children: [
            Container(
              width: 5,
              height: 5,
              decoration: BoxDecoration(
                  color: Color(color),
                  borderRadius: BorderRadius.circular(1)
              ),
            ),
            SizedBox(width: 4,),
            Text(
              "${type??""}${getStorageStr(size)}",
              style: TextStyle(
                  color: Color(0xFFBFC2CC),
                  fontSize: 11,
                  height: 1.2
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Widget _toMainPlaceHolderWidget() {
  //   return MixinPlaceHolderStatusWidget(
  //       emptyOnClick: () => viewModel?.refresh(),
  //       errorOnClick: () => viewModel.refresh(),
  //       child: _toFilterAndListWidget());
  // }

  Widget _toFilterAndListWidget() {
    // return Column(
    //   children: <Widget>[
    //     Offstage(
    //       offstage: data == null || data.isEmpty,
    //       child: MediaLibraryIndexFilterBarWidget(
    //         pageController: _pageController,
    //         totalValueNotifier: viewModel?.totalValueNotifier,
    //         onAddTap: throttle(()  async {
    //           _processUpload();
    //           await Future.delayed(Duration(milliseconds: 2000));
    //         }),
    //         onHandleTap: (){
    //           HandleMediaLibraryPage.navigatorPush(context);
    //         },
    //       ),
    //     ),
    //     Expanded(
    //       child: PageView(
    //         controller: _pageController,
    //         physics: ClampingScrollPhysics(),
    //         children: <Widget>[
    //           _toPlaceHolderWidget(
    //               child: MediaLibraryIndexGridPage(
    //                 list: data,
    //                 onTap: _onTap,
    //                 onDelete: _onDelete,
    //                 onUpateName: _onUpdateName,
    //                 canSelect: false,
    //               )),
    //           _toPlaceHolderWidget(
    //               child: MediaLibraryIndexGridPage(
    //                 list: data,
    //                 onTap: _onTap,
    //                 onDelete: _onDelete,
    //                 onUpateName: _onUpdateName,
    //                 canSelect: false,
    //               )),
    //           _toPlaceHolderWidget(
    //               child: MediaLibraryIndexGridPage(
    //                 list: data,
    //                 onTap: _onTap,
    //                 onDelete: _onDelete,
    //                 onUpateName: _onUpdateName,
    //                 canSelect: false,
    //               )),
    //         ],
    //       ),
    //     )
    //   ],
    // );
  }

  // Widget _toPlaceHolderWidget({Widget child}) {
  //   return  MixinPlaceHolderStatusWidget(
  //       emptyOnClick: () => viewModel?.refresh(),
  //       errorOnClick: () => viewModel.refresh(),
  //       // child: child,
  //       child: VgPullRefreshWidget.bind(
  //           state: this, viewModel: viewModel, child: child)
  //   );
  // }

  Widget _toEmptyWidget(){
    return VgPlaceHolderStatusWidget(
      emptyStatus: true,
      child: SizedBox(),
    );
  }

  void _onTap(MediaLibraryIndexListItemBean itemBean) {
    if (itemBean == null) {
      return null;
    }
    // VgPhotoPreview.listForPage(
    //   context,
    //   data,
    //   initUrl: itemBean?.picurl,
    //   urlTrasformFunc: (item) => item?.picurl,
    //   loadingTransformFunc: (item) => VgPhotoPreview.getImageQualityStr(
    //       item.getCoverUrl(), ImageQualityType.middleDown),
    // );
    if(itemBean.isHtml()){
      PosterDetailPage.navigatorPush(context, itemBean.htmlurl, itemBean.id,
          itemBean.likeflg, itemBean.cretype, "",  true,
          itemBean.logoflg, itemBean.addressflg, itemBean.diyflg, "02",
          itemBean.addressdiy, itemBean.namediy, itemBean.logodiy, itemBean.splpicurl, itemBean.pictype);
    }else{
      MediaDetailPage.navigatorPush(context, itemBean?.id, "02");
    }
  }

  void _onDelete(MediaLibraryIndexListItemBean itemBean) async {
    if (StringUtils.isEmpty(itemBean?.id)) {
      VgToastUtils.toast(context, "资源获取失败");
      return;
    }
    bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "所有终端显示屏中该文件都会删除，且不可找回，确认继续？",
        cancelText: "取消",
        confirmText: "删除",
        confirmBgColor:
        ThemeRepository.getInstance().getMinorRedColor_F95355());
    if (result ?? false) {
      viewModel?.deleteFolder(context, itemBean.id, itemBean?.videoid, itemBean?.getToDeletePicUrl(), (itemBean?.isVideo()??false)?(itemBean?.picurl??""):"");
    }
  }

  void _onUpdateName(MediaLibraryIndexListItemBean itemBean) {
    if (StringUtils.isEmpty(itemBean?.id)) {
      VgToastUtils.toast(context, "资源获取失败");
      return;
    }
    CommonEditWithTitleDialog.navigatorPushDialog(context,
        title: "重命名",
        confirmText: "确定",
        oldContent: itemBean.picname,
        onConfirm: (String content, VoidCallback popCallBack) {
          if (StringUtils.isEmpty(content)) {
            VgToastUtils.toast(context, "文件名不能为空");
            return;
          }
          VgToolUtils.removeAllFocus(context);
          viewModel?.updateFolderName(context, itemBean?.id, content, popCallBack);
        });
  }
  VideoPlayerController _videoController;
  ///处理视频的逻辑
  void handleVideo(String localUrl, List<UploadMediaLibraryItemBean> _uploadList)async{
    //视频
    UploadMediaLibraryItemBean item = UploadMediaLibraryItemBean(
      localUrl: localUrl, mediaType: MediaType.video,);

    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    item.videoLocalCover = tmpVideoCover;
    //
    try {
      _videoController = VideoPlayerController.file(file);
      await _videoController.initialize();
      item.videoDuration = _videoController?.value?.duration?.inSeconds;
      item.folderWidth = _videoController?.value?.size?.width?.floor();
      item.folderHeight = _videoController?.value?.size?.height?.floor();
      item.folderStorage = file.lengthSync();

      _uploadList.add(item);
      _videoController?.dispose();
      loading(false);
      if(_allTerminalSize == 0){
        _doUpload(_uploadList);
      }else{
        bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0]);
        if(result??false){
          viewModel?.refreshMultiPage();
        }
      }
    } catch (e) {
      loading(false);
      print("视频解析异常:" + e.toString());
      VgToastUtils.toast(context, "视频解析异常");
    }

  }

  ///处理图片的逻辑
  void handleImage(String localUrl, List<String> resultList, List<UploadMediaLibraryItemBean> _uploadList){
    //图片
    List<Future> taskList = resultList.reversed.map((element){
      FileImage image = FileImage(File(element));
      // 预先获取图片信息
      image
          .resolve(new ImageConfiguration())
          .addListener(new ImageStreamListener((ImageInfo info, bool _) async {
        double width = info.image.width + 0.0;
        double height = info.image.height + 0.0;

        if(width/height != 9.0/16.0){
          String clipPath = await MatisseUtil.clipOneImage(context,
              path: element, scaleX: 9, scaleY: 16,
              isCanMixRadio: true,
              // leftCancelWidget: _leftWidget(info, element, _uploadList, resultList.length),
              // rightClipWidget: _rightWidget(),
              topLeftWidget: _topLeftWidget(),
              keepRadioWidget: _keepWidget(info, element, _uploadList, resultList.length),
              rightTopClipWidget: _topRightWidget(),
              // editorConfig: pv.EditorConfig(
              //     maxScale: 8.0,
              //     cropRectPadding:
              //     EdgeInsets.all(30),
              //     hitTestSize: 0,
              //     lineColor: Colors.white,
              //     cornerSize: Size(0, 0),
              //     lineHeight: 2,
              //     cropAspectRatio: (9 ?? 1.0) / (16 ?? 1.0),
              //     editorMaskColorHandler: (context, bo) {
              //       return Color(0x80000000);
              //     }
              // ),
              onRequestPermission: (msg)async{
                bool result =
                await CommonConfirmCancelDialog.navigatorPushDialog(context,
                  title: "提示",
                  content: msg,
                  cancelText: "取消",
                  confirmText: "去授权",
                );
                if (result ?? false) {
                  PermissionUtil.openAppSettings();
                }
              }
          );
          if(clipPath == null){
            return;
          }
          if(StringUtils.isNotEmpty(clipPath)){
            FileImage clipImage = FileImage(File(clipPath));
            clipImage
                .resolve(new ImageConfiguration())
                .addListener(new ImageStreamListener((ImageInfo info, bool _) async {
              _uploadList.add(UploadMediaLibraryItemBean(
                  localUrl: clipPath,
                  mediaType: MediaType.image,
                  folderWidth: info.image.width,
                  folderHeight: info.image.height
              ));

              if(_uploadList.length == resultList.length){
                if(_allTerminalSize == 0){
                  _doUpload(_uploadList);
                }else{
                  bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0], itemList: _uploadList);
                  if(result??false){
                    viewModel?.refreshMultiPage();
                  }
                }
              }
            }));


          }else{
            if(_uploadList.length == resultList.length){
              _uploadList.add(UploadMediaLibraryItemBean(
                localUrl: localUrl,
                mediaType: MediaType.image,
                folderWidth: info.image.width,
                folderHeight: info.image.height,));
            }
          }
        }

        else{
          _uploadList.add(UploadMediaLibraryItemBean(
            localUrl: element,
            mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height,));

          if(_uploadList.length == resultList.length){
            if(_allTerminalSize == 0){
              _doUpload(_uploadList);
            }else{
              bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0], itemList: _uploadList);
              if(result??false){
                viewModel?.refreshMultiPage();
              }
            }
          }

        }
      }, onError: (dynamic exception, StackTrace stackTrace){
        print(exception.toString());
      }));

      return new Future((){
        print (element);
      });
    }).toList();
    // Future future = Future.wait(taskList);
    // future.then((value) async {
    //   if(_allTerminalSize == 0){
    //     _doUpload(_uploadList);
    //   }else{
    //     bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0], itemList: _uploadList);
    //     if(result??false){
    //       viewModel?.refreshMultiPage();
    //     }
    //   }
    // });
  }


  void _processUpload() async {
    List<String> resultList = await MatisseUtil.selectAll(
        context: context,
        isCanMixSelect: false,
        maxImageSize: 9,
        maxVideoSize: 1,
        videoMemoryLimit: 500*1024,
        videoDurationLimit: 10*60,
        videoDurationMinLimit: 10,
        maxAutoFinish: false,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }
    );
    if (resultList == null || resultList.isEmpty) {
      return;
    }

    List<UploadMediaLibraryItemBean> _uploadList = List();
    Map<String, ImageInfo> _imageInfoMap = new Map();
    //获取选择的图片或者视频
    String localUrl = resultList[0];
    if (StringUtils.isEmpty(localUrl)) {
      return;
    }
    if(resultList.length == 1 && MatisseUtil.isVideo(localUrl)){
      //处理视频逻辑
      loading(true, msg: "视频处理中");
      handleVideo(localUrl, _uploadList);
    }else {
      if(resultList.length > 1){
        loading(true, msg: "图片处理中");
        int needClipCount = 0;
        int computeCount = 0;
        resultList.forEach((element) {
          FileImage image = FileImage(File(element));
          image.resolve(new ImageConfiguration())
              .addListener(new ImageStreamListener((ImageInfo info, bool _) async{
            _imageInfoMap[element] = info;
            double width = info.image.width + 0.0;
            double height = info.image.height + 0.0;
            if(width/height != 9.0/16.0){
              needClipCount++;
            }
            computeCount++;
            if(computeCount == resultList.length){
              loading(false);
              if(needClipCount > 0){
                bool result =
                await CommonConfirmCancelDialog.navigatorPushDialog(context,
                    title: "提示",
                    content: "检测到${needClipCount}张图片长宽比不符合16:9，是否逐个裁剪处理？",
                    cancelText: "保持原比例",
                    confirmText: "去裁剪",
                    confirmBgColor: ThemeRepository.getInstance()
                        .getPrimaryColor_1890FF());
                //去裁剪
                if(result == null){
                  RouterUtils.pop(context);
                  return;
                }
                if (result ?? false) {
                  handleImage(localUrl, resultList, _uploadList);
                }else{
                  //保持原图比例
                  resultList.forEach((element) {
                    _uploadList.add(UploadMediaLibraryItemBean(
                      localUrl: element,
                      mediaType: MediaType.image,
                      folderWidth: _imageInfoMap[element].image.width,
                      folderHeight: _imageInfoMap[element].image.height,));
                  });
                  if(_allTerminalSize == 0){
                    _doUpload(_uploadList);
                  }else{
                    bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0], itemList: _uploadList);
                    if(result??false){
                      viewModel?.refreshMultiPage();
                    }
                  }
                }
              }else{
                //保持原图比例
                resultList.forEach((element) {
                  _uploadList.add(UploadMediaLibraryItemBean(
                    localUrl: element,
                    mediaType: MediaType.image,
                    folderWidth: _imageInfoMap[element].image.width,
                    folderHeight: _imageInfoMap[element].image.height,));
                });
                if(_allTerminalSize == 0){
                  _doUpload(_uploadList);
                }else{
                  bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0], itemList: _uploadList);
                  if(result??false){
                    viewModel?.refreshMultiPage();
                  }
                }
              }
            }
          }));
        });
      }else{
        handleImage(localUrl, resultList, _uploadList);
      }

    }
  }

  Future _getSingleTask(){
    return new Future((){

    });
  }

  _doUpload(List<UploadMediaLibraryItemBean> uploadList){
    MediaLibraryIndexService service =
    MediaLibraryIndexService().setList(uploadList);
    if (service != null) {
      VgHudUtils.show(context, "正在上传");
      if(uploadList.length > 1){
        //多图上传
        service.multiUpload(VgBaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgHudUtils.hide(AppMain.context);
          VgToastUtils.toast(AppMain.context, "上传完成");
          RouterUtils.pop(context);
          viewModel?.refreshMultiPage();
          viewModel?.getStorageInfo(context);
          viewModel?.getSelfStorageInfo(context);
          viewModel?.getPicNum(context);
        }, onError: (msg) {
          VgHudUtils.hide(context);
          print("MediaLibraryIndexPage上传失败:" + msg);
          VgToastUtils.toast(AppMain.context, "上传失败");
          RouterUtils.pop(context);
          viewModel?.refreshMultiPage();
          viewModel?.getStorageInfo(context);
          viewModel?.getSelfStorageInfo(context);
          viewModel?.getPicNum(context);
        }));
      }else{
        //单文件上传
        service.upload(VgBaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgHudUtils.hide(AppMain.context);
          print("MediaLibraryIndexPage上传完成1:");
          VgToastUtils.toast(AppMain.context, "上传完成");
          RouterUtils.pop(context);
          viewModel?.refreshMultiPage();
          viewModel?.getStorageInfo(context);
          viewModel?.getSelfStorageInfo(context);
          viewModel?.getPicNum(context);
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgHudUtils.hide(AppMain.context);
          print("MediaLibraryIndexPage上传失败1:" + msg);
          VgToastUtils.toast(AppMain.context, "上传失败");
          RouterUtils.pop(context);
          viewModel?.refreshMultiPage();
          viewModel?.getStorageInfo(context);
          viewModel?.getSelfStorageInfo(context);
          viewModel?.getPicNum(context);
        }));
      }

    }
  }

  Widget _leftWidget(ImageInfo info, String localUrl, List<UploadMediaLibraryItemBean> _uploadList, int totalSize){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if(StringUtils.isNotEmpty(localUrl)){
          _uploadList.add(UploadMediaLibraryItemBean(
            localUrl: localUrl,
            mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height,));
          if(_uploadList.length == totalSize){
            if(_allTerminalSize == 0){
              _doUpload(_uploadList);
            }else{
              RouterUtils.pop(context);
              bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0], itemList: _uploadList);
              if(result??false){
                viewModel?.refreshMultiPage();
              }
            }
          }else{
            RouterUtils.pop(context);
          }
        }
      },
      child: Container(
        padding: EdgeInsets.only(bottom: 7.5),
        child: Text(
          "保持原图比例",
          style: TextStyle(
              fontSize: 15,
              color: Colors.white
          ),
        ),
      ),
    );
  }

  Widget _topLeftWidget(){
    return ClickAnimateWidget(
      child: Container(
        width: 40,
        height: 44,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 15.6),
        child: Image.asset(
          "images/top_bar_back_ico.png",
          width: 9,
          color: VgColors.INPUT_BG_COLOR,
        ),
      ),
      scale: 1.4,
      onClick: () {
        // VgNavigatorUtils.pop(context);
        FocusScope.of(context).requestFocus(FocusNode());
        Navigator.of(context).maybePop();
      },
    );
  }

  Widget _rightWidget(){
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      width: 96,
      height: 36,
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      selectedTextStyle: TextStyle(
        color: Colors.white, fontSize: 15,),
      unSelectTextStyle: TextStyle(
        color: Colors.white, fontSize: 15,),
      text: "确定裁剪",
      textSize: 15,
    );
  }

  Widget _topRightWidget(){
    return Container(
      height: 23,
      width: 48,
      alignment: Alignment.center,
      margin: EdgeInsets.only(left: 15, right: 15, top: 11, bottom: 10),
      decoration: BoxDecoration(
        color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        borderRadius: BorderRadius.circular(11.5),
      ),
      child: Text(
        "确定",
        style: TextStyle(
            fontSize: 12,
            color: Colors.white
        ),
      ),
    );
  }


  Widget _keepWidget(ImageInfo info, String localUrl, List<UploadMediaLibraryItemBean> _uploadList, int totalSize){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if(StringUtils.isNotEmpty(localUrl)){
          _uploadList.add(UploadMediaLibraryItemBean(
            localUrl: localUrl,
            mediaType: MediaType.image,
            folderWidth: info.image.width,
            folderHeight: info.image.height,));
          if(_uploadList.length == totalSize){
            if(_allTerminalSize == 0){
              _doUpload(_uploadList);
            }else{
              RouterUtils.pop(context);
              bool result = await MediaSettingsPage.navigatorPush(context, _uploadList[0], itemList: _uploadList);
              if(result??false){
                viewModel?.refreshMultiPage();
              }
            }
          }else{
            RouterUtils.pop(context);
          }
        }
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 5, vertical: 22),
        child: Container(
          height: 21.5,
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
          alignment: Alignment.center,
          child: Text(
            "原始比例",
            style: TextStyle(color: Color(0xffaaaaaa), fontSize: 12, height: Platform.isIOS ? 1.2 : 1.15),
          ),
        ),
      ),
    );
  }


  @override
  bool get wantKeepAlive => true;
}
